<template>
  <div class="Box">
    <!-- 搜索 -->
    <div class="SearchBox flex-H" v-show="tableData.length>0">
      <el-input
        v-model="SearchUser.searchValue"
        placeholder="请输入搜索内容"
        class="input-with-select"
        @keyup.enter="SearchUserList"
      >
        <template #prepend>
          <el-select v-model="SearchUser.selectKey" style="width: 6.25rem">
            <el-option label="用户ID" value="id" />
            <el-option label="用户名" value="Name" />
            <el-option label="账号" value="username" />
            <el-option label="电话" value="phoneA" />
            <el-option label="邮箱" value="email" />
            <el-option label="状态" value="status" />
          </el-select>
        </template>
        <template #append>
          <el-button :icon="Search" @click="SearchUserList" />
        </template>
      </el-input>
    </div>
    <!-- 分页 -->
    <div class="PageBox">
      <el-pagination
        :hide-on-single-page="true"
        v-model:current-page="page.currentPage"
        v-model:page="page.pageNum"
        v-model:limit="page.pageSize"
        v-model:total="page.total"
        :page-count="Math.ceil(page.total / page.pageSize)"
      />
    </div>
    <!-- 表格 -->
    <div class="TableBox">
      <cy-table
        class="Table"
        row-key="id"
        :data="tableData"
        :columns="ruleTable.columns"
        :loading="loading"
        @selection-change="handleSelectionChange"
      />
    </div>
    <!-- 修改抽屉 -->
    <el-drawer v-model="drawer" title="I am the title" :with-header="false">
      <el-form
        class="EditForm"
        :model="form"
        label-width="auto"
        style="max-width: 31.25rem"
      >
        <el-form-item label="用户">
          <el-input v-model="form.Name" disabled />
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input v-model="form.id" disabled />
        </el-form-item>
        <el-form-item label="用户账号">
          <el-input v-model="form.username" disabled />
        </el-form-item>
        <el-form-item label="用户密码">
          <el-input v-model="form.password" />
        </el-form-item>
        <el-form-item label="用户电话">
          <el-input v-model="form.phoneA" />
        </el-form-item>
        <el-form-item label="用户邮箱">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="激活" value="1" />
            <el-option label="注销" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">确认</el-button>
          <el-button @click="drawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script lang="tsx" setup>
import { ref, reactive, watch, onMounted } from "vue";
import type { TableInstance } from "element-plus";

import CyTable from "@/components/table";

import { ElMessage, ElMessageBox, VLoad } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import {
  getUserAllAPI,
  getUserPageAPI,
  getUserKeyPageAPI,
  UpdateUserByIdAPI,
  DeleteUserByIdAPI,
  DeleteUserMoreByIdAPI,
} from "@/api/user";
import { assignObject } from "@/utils/object";
const tableData: User[] = ref([]);
const tableRef = ref<TableInstance>();
const loading = ref(true);
const multipleSelection = ref<User[]>([]);
const drawer = ref(false);
interface User {
  id: number;
  Name: string;
  username: string;
  password: string;
  phoneA: string;
  email: string;
  status: string;
}
const page = reactive({
  currentPage: 1,
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
// 修改表单
const form = reactive({
  id: "",
  Name: "",
  username: "",
  password: "",
  phoneA: "",
  email: "",
  status: "",
});
// 筛选
const SearchUser = reactive({
  selectKey: "id",
  searchValue: "",
});
// 表格配置
const ruleTable = reactive({
  columns: [
    // 全选框列
    {
      type: "selection",
      width: 55,
      selectable: (row: User, index: number) => ![1].includes(row.id),
    },
    // 数据列
    { prop: "id", label: "ID", width: 120 },
    { prop: "Name", label: "用户", width: 120 },
    { prop: "username", label: "账号" },
    { prop: "password", label: "密码" },
    { prop: "phoneA", label: "电话" },
    { prop: "email", label: "邮箱" },
    // 状态列
    {
      prop: "status",
      label: "状态",
      width: 70,
      // 筛选配置
      filterable: true,
      filters: [
        { text: "已激活", value: "1" },
        { text: "未激活", value: "0" },
      ],
      // 筛选方法
      filterMethod: (value, row) => {
        return row.status === value;
      },
      render: ({ row }) => (
        <span class={UserStatus(row.status)}>
          {row.status === "1" ? "已激活" : "未激活"}
        </span>
      ),
    },
    // 操作列
    {
      label: "操作",
      align: "center",
      headerRender: () => (
        <div style="text-align: center;">
          <div class="OptionsBtn" onClick={MoreDelete} style="display: inline-block;">
            批量删除
          </div>
        </div>
      ),
      render: ({ row, index }) => (
        <div>
          <el-button onClick={() => handleEdit(index, row)}>修改</el-button>
          <el-button type="danger" onClick={() => handleDelete(index, row)}>
            删除
          </el-button>
        </div>
      ),
    },
  ],
});

// 分页查询
const getUserPage = () => {
  loading.value = true;
  getUserPageAPI({ page: page.currentPage, pageSize: page.pageSize })
    .then((res) => {
      const { row, total } = res.data;
      tableData.value = row;
      page.total = total;
    })
    .finally(() => (loading.value = false));
};
// 选择框选中
const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val;
};
// 修改
const handleEdit = (index: number, row: User) => {
  if (row.id === 1) {
    // 管理员账号取消操作
    ElMessage.warning("无权限操作");
    return;
  }
  assignObject(form, row);
  drawer.value = true;
};
// 删除
const handleDelete = (index: number, row: User) => {
  if (row.id === 1) {
    // 管理员账号取消操作
    ElMessage.warning("无权限操作");
    return;
  }
  // 警告提示
  ElMessageBox.confirm("删除操作无法撤回，是否继续?", "Warning", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning",
  })
    .then(() => {
      // 执行删除
      DeleteUserByIdAPI(row.id).then((res) => {
        const { code, message } = res.data;
        getUserPage();
        ElMessage.success(message);
      });
    })
    .catch(() => {
      // 取消
      ElMessage({
        type: "info",
        message: "取消删除操作",
      });
    });
};
// 批量删除
const MoreDelete = () => {
  if (!multipleSelection.value || multipleSelection.value.length === 0) {
    ElMessage.warning("未选择目标");
    return;
  }
  const ids = multipleSelection.value.reduce(
    (acc, user) => [...acc, user.id],
    []
  );
  // 警告提示
  ElMessageBox.confirm("删除操作无法撤回，是否继续?", "Warning", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning",
  })
    .then(() => {
      // 执行删除
      DeleteUserMoreByIdAPI(ids).then((res) => {
        const { code, message } = res.data;
        getUserPage();
        ElMessage.success(message);
      });
    })
    .catch(() => {
      // 取消
      ElMessage({
        type: "info",
        message: "取消删除操作",
      });
    });
};
// 确认修改提交
const onSubmit = () => {
  UpdateUserByIdAPI(form).then((res) => {
    const { code, message } = res.data;
    getUserPage();
    ElMessage.success(message);
    drawer.value = false;
  });
};
// 状态文本转实际值
const selectMap = (value:string) => {
  const Active=['1','激活','已激活','启用']
  const UnActive=['0','未激活','禁用']
  if(Active.includes(value)){
    return '1'
  }
  if(UnActive.includes(value)){
    return '0'
  }
  return value // 找不到匹配则返回原值
}
// 条件查询
const SearchUserList = () => {
  if (!SearchUser.searchValue) {
    getUserPage();
    return;
  }
  getUserKeyPageAPI({
    SearchKey: SearchUser.selectKey,
    SearchValue: selectMap(SearchUser.searchValue),
    page: page.currentPage,
    pageSize: page.pageSize,
  }).then((res) => {
    const { row, total } = res.data;
    tableData.value = row;
    page.total = total;
  });
};
// 用户状态动态类名
const UserStatus = (userStatus: string) => {
  switch (userStatus) {
    case "1":
      return "status-active";
    default:
      return "status-unactive";
  }
};
// 监听分页
watch(
  () => page.currentPage,
  () => {
    if(!SearchUser.searchValue){
      getUserPage();
    }else{
      SearchUserList()
    }
  }
);
onMounted(() => {
  setTimeout(() => {
    getUserPage();
  }, 1000);
});
</script>
<style scoped lang="scss">
.Box {
  position: relative;
  .SearchBox {
    width: 100%;
    height: 60px;
    background-color: #fff;
    border-bottom: 1px solid #eee;
    .el-input {
      width: 350px;
      margin-left: 0.5rem;
    }
  }
  .PageBox {
    background-color: #fff;
    padding-left: 30%;
    margin: 1rem;
  }
  .TableBox {
    .Table {
      width: 100%;
      min-height: 25rem;
      border-top: 1px solid #eee;
    }
    :deep(.status-active) {
      color: green;
    }
    :deep(.status-unactive) {
      color: #f56c6c;
    }
    :deep(.OptionsBtn) {
      height: 30px;
      line-height: 30px;
      width: 8.125rem;
      border: 1px solid #f56c6c;
      border-radius: 0.3rem;
      text-align: center;
      background-color: #f56c6c;
      color: #fff;
      cursor: pointer;
      &:hover {
        background-color: #e78d8d;
        border: 1px solid #e78d8d;
      }
    }
  }

  .EditForm {
    :deep(.el-form-item__content) {
      display: flex;
      justify-content: center;
      align-content: center;
    }
  }
}
</style>
